package cn.ham.dao.impl;

import cn.ham.dao.ProjectDao;
import cn.ham.entity.Project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 18号
 * @date 2016/11/26 19:03
 */
@Repository
public class ProjectDaoImpl implements ProjectDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(final Project project) {
        final  String sql = "INSERT INTO project (name, rely_url,api_url) VALUES (?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1,project.getName());
                ps.setObject(2,project.getRelyUrl());
                ps.setObject(3,project.getApiUrl());
                return ps;
            }
        },keyHolder);
        int id = keyHolder.getKey().intValue();
        return id;
    }

    @Override
    public List<Project> selectAll() {
        List result = jdbcTemplate.query("SELECT id,name,rely_url as relyUrl,api_url as apiUrl FROM project",
                new BeanPropertyRowMapper(Project.class));
        return result;
    }

    @Override
    public Project selectById(int proId) {

        List result = jdbcTemplate.query("SELECT id,name,rely_url as relyUrl,api_url as apiUrl FROM project WHERE id = ?",
                new BeanPropertyRowMapper(Project.class),proId);
        return (Project) result.get(0);
    }
}
